package org.richin.file.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

/**
 * 统计文件夹下的文件数量
 * 
 * @author Administrator
 * 
 */
public class FileCounter {
	/** 文件夹总数，初始化为-1，不包括根目录 */
	private int folderCnt = -1;

	/**
	 * 文件总数
	 */
	private int fileCnt = 0;

	/**
	 * 图片总数
	 */
	private int imgCnt = 0;

	public FileCounter() {
	}

	public FileCounter(File path) {
	}

	public FileCounter(String path) {
	}

	public void count(String path) {
		File file = new File(path);
		if (file.exists() && file.isDirectory()) {
			count(file);
		} else {
			System.out.println("Bad input parameters.");
			return;
		}
		System.out.println("There are " + folderCnt + " folder(s).");
		System.out.println("There are " + fileCnt + " file(s).");
		System.out.println("There are " + imgCnt + " image(s).");

	}

	private void count(File path) {
		// 如果是文件夹，则递归调用
		if (path.isDirectory()) {
			folderCnt++;
			File[] files = path.listFiles();
			for (File file : files) {
				count(file);
			}
		} else {
			// 文件数增加1
			fileCnt++;

			// 根据扩展名判断是否是图片。
			if (path.getName().endsWith("jpg")
					|| path.getName().endsWith("jpeg")) {
				imgCnt++;
			}
		}
	}

	/**
	 * 计算文件夹大小
	 * 
	 * @param dir
	 * @return
	 */
	public static final long getDirectorySize(File directory) {
		long retSize = 0;
		if ((directory == null) || !directory.exists()) {
			String message = directory + " does not exist";
			throw new IllegalArgumentException(message);
		}
		if (!directory.isDirectory()) {
			String message = directory + " is not a directory";
			throw new IllegalArgumentException(message);
		}
		File[] files = directory.listFiles();
        if (files == null) {  // null if security restricted
            return 0L;
        }
		int count = files.length-1;
		for (int i = count; i >=0; i--) {
			if (files[i].isDirectory()) {
				retSize += getDirectorySize(files[i]);
			} else {
				retSize += files[i].length();
			}
		}
		return retSize;
	}// System.out.println(FileUtils.byteCountToDisplaySize(getDirectorySize("d:/umemo")));

	public static final long getDirectorySize(String dir) {
		return getDirectorySize(new File(dir));
	}// System.out.println(getDirectorySize("d:/umemo"));
	/**
	 * 返回文件夹大小用 GB MB KB显示
	 * @param size
	 * @return
	 */
	public static String byteCountToDisplaySize(long size) {
		return FileUtils.byteCountToDisplaySize(size);
		
	}
	public static void main(String[] args) throws MalformedURLException,
			IOException {
		// FileCounter fileCounter = new FileCounter();
		// /fileCounter.count("d:/umemo");
		System.out.println((getDirectorySize("d:/umemo")));
	}

}
